﻿namespace Blaze.Framework.LuaExtensions.FileLoaders
{
    using System;
    using System.IO;
    using EditorOnly;
    using Security;

    /// <summary>
    /// 基于目录的Lua文件加载器。
    /// </summary>
    public class FromDirectory
    {
        public FromDirectory(string rootPath)
        {
            mRootPath = rootPath;
        }

        public byte[] ReadFile(ref string filePath)
        {
            var bytes = readFile(ref filePath);
            if (bytes == null)
                return null;
            using (var memoryStream = new MemoryStream(bytes))
            {
                using (var stream = new DecryptionStream(memoryStream))
                {
                    var ret = new byte[stream.Length];
                    stream.Read(ret, 0, ret.Length);
                    return ret;
                }
            }
        }

        private byte[] readFile(ref string filePath)
        {
            filePath = filePath.Replace(".", "/");
            var ret = readFileInternal(string.Format("{0}/{1}.lua", mRootPath, filePath), ref filePath);
            if (ret == null)
                ret = readFileInternal(string.Format("{0}/{1}/init.lua", mRootPath, filePath), ref filePath);
            return ret;
        }

        private byte[] readFileInternal(string fullPath, ref string filePath)
        {
            if (!File.Exists(fullPath))
                return null;
#if UNITY_EDITOR_WIN
            var physicalPath = ProjectPath.GetWindowsPhysicalPath(fullPath);
            if (fullPath != physicalPath)
                throw new ArgumentException("路径大小写错误：\n" + fullPath + "\n" + physicalPath);
#endif
            filePath = fullPath;
            return File.ReadAllBytes(fullPath);
        }

        private readonly string mRootPath;
    }
}